import {_decorator, Component, Node, Button, EventHandler, CCInteger} from 'cc';

const {ccclass, property} = _decorator;

@ccclass('ButtonPlus')
export class ButtonPlus extends Button {

    @property({type: CCInteger, tooltip: '长按触发长按的时长', displayName: '触发长按的时长(s)', step: 0.1})
    public btn_hover_time: number = 1.0;// hover的时长,监听长按触发长按的总时间
    @property({
        type: EventHandler,
        tooltip: "触发长按后的回调函数\\n当前节点有长按事件，则触发所有事件",
        displayName: '长按事件'
    })
    public longTouchEvents: EventHandler[] = [];//长按事件

    @property({
        type: EventHandler,
        tooltip: "触发点击后的回调函数\\n当前节点有点击事件，则触发所有事件",
        displayName: '点击事件'
    })
    public clickEvents: EventHandler[] = []; // 点击事件

    @property({
        type: EventHandler,
        tooltip: "触发长按松手后的回调函数\\n当前节点有松手事件，则触发所有事件",
        displayName: '长按松手事件'
    })
    public longTouchCanelEvents: EventHandler[] = []; // 点击事件

    private _touchStartTime: number = 0; // 记录触摸开始的时间

    start() {

    }

    update(deltaTime: number) {

    }

    onEnable() {
        this.node.on(Node.EventType.TOUCH_START, this._onTouchStartPlus, this);
        this.node.on(Node.EventType.TOUCH_END, this._onTouchEndPlus, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this._onTouchCancelPlus, this);
    }

    onDisable() {
        this.node.off(Node.EventType.TOUCH_START, this._onTouchStartPlus, this);
        this.node.off(Node.EventType.TOUCH_END, this._onTouchEndPlus, this);
        this.node.off(Node.EventType.TOUCH_CANCEL, this._onTouchCancelPlus, this);
    }

    private _onTouchStartPlus() {
        // console.log("长按开始");
        this._touchStartTime = Date.now(); // 记录触摸开始的时间
        this.schedule(this._trigger_events, this.btn_hover_time);
    }

    private _onTouchEndPlus() {
        console.log("长按结束")
        // console.log("长按结束");
        //this.unschedule(this._trigger_events)
        const touchDuration = Date.now() - this._touchStartTime; // 计算触摸持续时间
        this.unschedule(this._trigger_events);

        if (touchDuration < this.btn_hover_time * 1000) {
            // 如果触摸时间小于长按时间，则触发点击事件
            this.scheduleOnce(this._clickEvents, 0);

        } else {
            this.scheduleOnce(this._longTouchEvents, 0);
        }
    }

    private _onTouchCancelPlus() {
        this.unschedule(this._trigger_events)
    }

    private _longTouchEvents() {
        EventHandler.emitEvents(this.longTouchCanelEvents);
    }

    private _clickEvents() {
        console.log("执行点击方法")
        EventHandler.emitEvents(this.clickEvents);
    }

    private _trigger_events() {
        EventHandler.emitEvents(this.longTouchEvents)
    }
}


